package pers.cz.selenium.component;

import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.RemoteWebDriver;
import pers.cz.thread.ThreadUtils;

/**
 * @program: PostGirl-panent
 * @description: 切换组件， 用来切换到最新页面或者最新iframe
 * @author: Cheng Zhi
 * @create: 2023-01-23 13:51
 **/
public class SwitchComponent extends AbstractComponent{

    private RemoteWebDriver driver;
    private ContextComponent contextComponent;
    public SwitchComponent(RemoteWebDriver driver) {
        this.driver = driver;
        this.contextComponent = new ContextComponent(driver);
        init();
    }

    @Override
    public WebElement initWebElement() {
        return null;
    }

    @Override
    public RemoteWebDriver initDriver() {
        return driver;
    }

    public boolean switchNewPage() {
        return contextComponent.switchNewWin();
    }

    public boolean switchNewIframe() {
        return contextComponent.switchNewIframe();
    }

    /**
     * 切换到指定窗口
     * @param pageNum
     * @return
     */
    public boolean switchPage(Integer pageNum) {
        try {
            ThreadUtils.doSleep(5000L);
            if (contextComponent.isHaveAlert()) {
                // 把弹框点掉
                driver.switchTo().alert().accept();
            }
            String lastHandle = null;
            int i=1;
            for (String handle : driver.getWindowHandles()) {
                if (i == pageNum) {
                    lastHandle = handle;
                }
                i ++;
            }
            driver.switchTo().window(lastHandle);
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return false;
        }
    }
}
